<template>
  <section class="page-container">
    <el-form 
      :model="ruleForm" 
      :label-position="labelPosition" 
      :rules="rules" 
      ref="ruleForm" 
      label-width="100px" 
      class="demo-ruleForm">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="ruleForm.title" placeholder="请输入文章标题"></el-input>
      </el-form-item>
      <el-form-item label="关键词" prop="keywords" >
        <el-input v-model="ruleForm.keywords" placeholder="填写关键词有利于搜素引擎收录，多个用逗号隔开"></el-input>
      </el-form-item>
      <el-form-item label="文章描述" prop="description" label-position="top">
        <el-input type="textarea" v-model="ruleForm.description" placeholder="请输入文章描述"></el-input>
      </el-form-item>
      <el-form-item label="缩略图" prop="thumb">
        <el-upload
          class="avatar-uploader"
          :action="$serverUrl + '/api/upload/thumbImage'"
          :data="{width: 300, height: 300, folder: 'post'}"
          accept="image/*"
          :show-file-list="false"
          :on-success="handleThumbUploadSuccess"
          :before-upload="beforeThumbUpload">
          <img v-if="ruleForm.thumb" :src="$serverUrl + '/storage/' + ruleForm.thumb" class="upload-thumb">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="body" label-position="top">
        <tinymce :height=400 ref="editor" v-model="ruleForm.body"></tinymce>
      </el-form-item>
      <el-form-item label="文章分类" prop="category_id"
      >
        <el-select v-model.number="ruleForm.category_id" placeholder="请选择文章分类">
          <el-option
            v-for="item in categories"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否发布" prop="is_published">
        <el-switch active-text="" inactive-text="" v-model="ruleForm.is_published"></el-switch>
      </el-form-item>

      <el-form-item label="点击数量" prop="pv">
        <el-input v-model="ruleForm.pv" disabled></el-input>
      </el-form-item>

      <el-form-item label="文章来源" prop="from">
        <el-input v-model="ruleForm.from"></el-input>
      </el-form-item>

      <el-form-item label="文章编辑" prop="editor">
        <el-input v-model="ruleForm.editor"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </section>
</template>
<script>
  import Tinymce from '@/components/tinymce/Editor'
  export default {
    data () {
      return {
        labelPosition: 'right',
        ruleForm: {},
        tempData: {
          title: '',
          keywords: '',
          description: '',
          body: '',
          is_published: true,
          category_id: '',
          thumb: '',
          from: '天南山文化',
          pv: 0,
          editor: '管理员'
        },
        rules: {
          title: [
            { required: true, message: '请输入标题', trigger: 'blur' },
            { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
          ],
          body: [
            {required: true, message: '请输入文章内容', trigger: 'blur'}
          ],
          description: [
            { required: true, message: '请填写文章描述', trigger: 'blur' }
          ],
          category_id: [
            {required: true, type: 'number', message: '请选择文章分类', trigger: 'blur'}
          ],
          thumb: [
            { required: true, message: '请上传缩略图', trigger: 'blur' }
          ]
        },
        categories: {}
      }
    },
    components: { Tinymce },
    methods: {
      handleThumbUploadSuccess (res, file) {
        this.ruleForm.thumb = res
      },
      beforeThumbUpload (file) {
        const sizeLimit = file.size / 1024 / 1024 < 0.5
        if (!sizeLimit) {
          this.$message.error('上传图片大小不能超过0.5MB!')
        }
        return sizeLimit
      },
      submitForm (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this._createOrEdit()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      resetForm (formName) {
        this.$refs[formName].resetFields()
      },
      _getCategories () {
        this.$http.get('/categories?belongs_to=post').then((response) => {
          this.categories = response.data
        }).catch((error) => {
          console.log(error)
        })
      },
      _createOrEdit () {
        this.$http({
          method: this.isEdit ? 'put' : 'post',
          url: this.isEdit ? '/posts/' + this.ruleForm.id : '/posts',
          data: this.ruleForm
        }).then((response) => {
          this.$message.success('保存成功')
          this.$router.push('/post/index')
        }).catch((error) => {
          console.log(error)
        })
      },
      _restFormData () {
        this.ruleForm = Object.assign({}, this.tempData)
      },
      _getData () {
        this.$http.get('/posts/' + this.$route.params.id + '/edit').then((response) => {
          this.ruleForm = response.data
          // this.editor && this.editor.txt.html(response.data.body)
        }).catch((error) => {
          console.log(error)
        })
      }
    },
    computed: {
      isEdit () {
        return this.$route.meta.isEdit
      }
    },
    watch: {
      '$route' (to, from) {
        if (!to.meta.isEdit) {
          this._restFormData()
        } else {
          this._getData()
        }
      }
    },
    mounted () {
      this._restFormData()
      this._getCategories()
      if (this.isEdit) {
        this._getData()
      }
    }
  }
</script>
<style lang="scss" scoped>
  .page-container {
    padding: 20px 50px;
  }
</style>